<template>
    <view>
        <!-- 使用 lime-painter 生成海报 -->
        <l-painter 
            v-if="posterConfig"
            ref="limePainter"
            :board="posterConfig"
            :hidden="true"
            :is-canvas-to-temp-file-path="false"
            :custom-style="'position: fixed; left: -9999rpx; top: -9999rpx;'"
            @success="bindPosterSuccessListener"
            @fail="bindPosterFailListener"
            @done="bindPosterDoneListener"
            file-type="jpg"
            path-type="url"
            :pixel-ratio="2"
            :use-c-o-r-s="true"
        />

        <!-- 海报显示弹窗 -->
        <view @touchmove.stop.prevent="trueFun" style="z-index: 9999999999" :class="'main-poster modal bottom-modal ' + (showClone ? 'show' : '')">
            <view class="dialog">
                <view class="poster-img" v-if="isCreate">
                    <image
                        @tap="handleImageTap"
                        data-type="img"
                        :data-url="imgClone"
                        :show-menu-by-longpress="true"
                        v-if="isLoad"
                        mode="widthFix"
                        :src="imgClone"
                        class="shadow loading"
                    ></image>

                    <view v-else class="load loading text-l"></view>

                    <view class="save-hint text-project" v-if="isLoad">长按图片保存或者转发</view>
                </view>
                <view class="poster-share">
                    <button class="item item-share clearbtn" open-type="share" :data-img="imgClone">
                        <view class="pic">
                            <image src="/static/cmpts/public/poster/images/wechat.png" />
                        </view>
                        <text>转发给朋友</text>
                    </button>

                    <view v-if="doPoster" class="item" @tap="bindPosterTap" style="padding-top: 12rpx">
                        <view class="pic">
                            <image class="friend" src="/static/cmpts/public/poster/images/friend.png" />
                        </view>
                        <text>生成海报</text>
                    </view>
                </view>

                <view class="line" @tap="bindCloseTap">
                    <view>关闭</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
const pageHelper = require('@/utils/helper/page_helper.js');
const picHelper = require('@/utils/helper/pic_helper.js');
const helper = require('@/utils/helper/helper.js');

export default {
    data() {
        return {
            isLoad: false,
            isCreate: false,
            posterConfig: null,
            showClone: false,
            imgClone: '',
            debug: false // 是否显示调试画板
        };
    },
    props: {
        config: {
            // 海报配置对象
            type: Object,
            default: null
        },
        show: {
            // 显示弹窗
            type: Boolean,
            default: false
        },
        img: {
            // 图片文件路径
            type: String,
            default: ''
        },
        doPoster: {
            type: Boolean,
            default: true
        }
    },
    mounted() {
        this.initFun();
    },
    methods: {
        initFun: function () {
            // 初始化
            if (this.config) {
                this.generatePosterConfig();
            }
        },

        // 根据传入配置生成 lime-painter 配置
        generatePosterConfig() {
            if (!this.config) return;

            console.log('生成海报配置:', this.config);
            
            // 如果传入的已经是 lime-painter 配置格式，直接使用
            if (this.config.css && this.config.views) {
                this.posterConfig = this.config;
                console.log('使用传入的 lime-painter 配置');
                return;
            }
            
            const { 
                cover, 
                title, 
                desc, 
                qr, 
                user = '', 
                avatar = '',
                bg = 'linear-gradient(180deg,#ff971b 0%, #ff5000 100%)'
            } = this.config;

            // 生成 lime-painter 的 JSON 配置
            this.posterConfig = {
                css: {
                    width: '750rpx',
                    paddingBottom: '40rpx',
                    background: bg || 'linear-gradient(180deg,#ff971b 0%, #ff5000 100%)'
                },
                views: []
            };

            // 添加头像
            if (avatar) {
                this.posterConfig.views.push({
                    src: avatar || '/static/images/share.jpg',
                    type: 'image',
                    css: {
                        background: '#ffffff',
                        objectFit: 'cover',
                        marginLeft: '40rpx',
                        marginTop: '40rpx',
                        width: '84rpx',
                        border: '2rpx solid #ffffff',
                        boxSizing: 'border-box',
                        height: '84rpx',
                        borderRadius: '50%'
                    }
                });
            }

            // 添加用户信息
            if (user) {
                this.posterConfig.views.push({
                    type: 'view',
                    css: {
                        marginTop: '40rpx',
                        paddingLeft: '20rpx',
                        display: 'inline-block'
                    },
                    views: [
                        {
                            text: user,
                            type: 'text',
                            css: {
                                display: 'block',
                                paddingBottom: '10rpx',
                                color: '#ffffff',
                                fontSize: '32rpx',
                                fontWeight: 'bold'
                            }
                        },
                        {
                            text: '为您推荐了一个好物',
                            type: 'text',
                            css: {
                                color: 'rgba(255,255,255,.7)',
                                fontSize: '24rpx'
                            }
                        }
                    ]
                });
            }

            // 添加内容卡片
            const cardViews = [];

            // 封面图片
            console.log('cover', cover);
            if (cover) {
                cardViews.push({
                    src: cover || '/static/images/share.jpg',
                    type: 'image',
                    css: {
                        objectFit: 'cover',
                        objectPosition: '50% 50%',
                        width: '606rpx',
                        height: '400rpx',
                        borderRadius: '12rpx'
                    }
                });
            }

            // 标题和描述
            if (title || desc) {
                const contentView = {
                    css: {
                        marginTop: '30rpx',
                        display: 'flex',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'flex-start'
                    },
                    views: [],
                    type: 'view'
                };

                // 文字内容
                const textContent = {
                    css: {
                        flex: 1,
                        paddingRight: '20rpx',
                        boxSizing: 'border-box'
                    },
                    views: [],
                    type: 'view'
                };

                if (title) {
                    textContent.views.push({
                        text: title,
                        type: 'text',
                        css: {
                            display: 'block',
                            lineClamp: 2,
                            color: '#333333',
                            lineHeight: '1.5em',
                            fontSize: '36rpx',
                            fontWeight: 'bold',
                            marginBottom: '10rpx'
                        }
                    });
                }

                if (desc) {
                    textContent.views.push({
                        text: desc,
                        type: 'text',
                        css: {
                            display: 'block',
                            lineClamp: 3,
                            color: '#666666',
                            lineHeight: '1.4em',
                            fontSize: '28rpx'
                        }
                    });
                }

                contentView.views.push(textContent);

                // 二维码
                if (qr) {
                    contentView.views.push({
                        text: qr,
                        type: 'qrcode',
                        css: {
                            width: '128rpx',
                            height: '128rpx',
                            background: '#ffffff'
                        }
                    });
                }

                cardViews.push(contentView);
            }

            // 添加内容卡片容器
            if (cardViews.length > 0) {
                this.posterConfig.views.push({
                    css: {
                        marginLeft: '40rpx',
                        marginTop: '30rpx',
                        padding: '32rpx',
                        boxSizing: 'border-box',
                        background: '#ffffff',
                        borderRadius: '16rpx',
                        width: '670rpx',
                        boxShadow: '0 20rpx 58rpx rgba(0,0,0,.15)'
                    },
                    views: cardViews,
                    type: 'view'
                });
            }

            console.log('生成的海报配置:', JSON.stringify(this.posterConfig, null, 2));
        },

        bindPosterTap: function () {
            this.setData({
                isCreate: true,
                isLoad: false
            }, () => {
                this.createPoster();
            });
        },

        bindCloseTap: function () {
            this.setData({
                showClone: false
            });
        },

        // 生成海报
        createPoster: async function () {
            if (!this.posterConfig) {
                console.error('海报配置不存在');
                uni.showToast({
                    title: '海报配置错误',
                    icon: 'none'
                });
                this.setData({
                    isCreate: false,
                    isLoad: false
                });
                return;
            }

            try {
                console.log('开始生成海报...');
                
                // 等待一小段时间确保组件已渲染
                await new Promise(resolve => setTimeout(resolve, 500));
                
                if (!this.$refs.limePainter) {
                    throw new Error('lime-painter 组件引用不存在');
                }

                // 使用 lime-painter 生成图片
                const options = {
                    fileType: 'jpg',
                    quality: 0.8,
                    success: (res) => {
                        console.log('海报生成成功:', res.tempFilePath);
                        this.setData({
                            imgClone: res.tempFilePath,
                            isLoad: true
                        });
                    },
                    fail: (err) => {
                        console.error('海报生成失败:', err);
                        this.bindPosterFailListener({ detail: err });
                    }
                };
                
                // H5环境下使用base64，其他环境使用url
                // #ifdef H5
                options.pathType = 'base64';
                // #endif
                // #ifndef H5
                options.pathType = 'url';
                // #endif
                
                this.$refs.limePainter.canvasToTempFilePathSync(options);
            } catch (error) {
                console.error('海报生成异常:', error);
                this.bindPosterFailListener({ detail: error });
            }
        },

        bindPosterSuccessListener(tempFilePath) {
            console.log('lime-painter 生成成功:', tempFilePath);
            this.setData({
                imgClone: tempFilePath,
                isLoad: true
            });
        },

        bindPosterFailListener(error) {
            console.error('lime-painter 生成失败:', error);
            
            // 显示错误提示
            uni.showToast({
                title: '海报生成失败，请检查配置',
                icon: 'none',
                duration: 3000
            });
            
            // 重置状态
            this.setData({
                isCreate: false,
                isLoad: false
            });
        },

        bindPosterDoneListener() {
            console.log('lime-painter 绘制完成');
        },

        handleImageTap: function (e) {
            // 处理图片点击事件
            console.log('图片被点击:', e);
            if (pageHelper && pageHelper.url) {
                pageHelper.url(e, this);
            }
        },

        bindSaveTap: function (e) {
            let that = this;
            let callback = function () {
                uni.saveImageToPhotosAlbum({
                    filePath: that.imgClone,
                    success: function (data) {
                        uni.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 1000
                        });
                    }
                });
            };
            picHelper.getWritePhotosAlbum(callback);
        },

        trueFun() {
            console.log('占位：函数 true 未声明');
        },

        // 数据更新方法，兼容原有组件
        setData(data, callback) {
            Object.keys(data).forEach(key => {
                this[key] = data[key];
            });
            this.$nextTick(() => {
                if (callback && typeof callback === 'function') {
                    callback();
                }
            });
        }
    },
    watch: {
        show: {
            handler: function (newVal) {
                this.showClone = newVal;
            },
            immediate: true
        },

        img: {
            handler: function (newVal) {
                this.imgClone = newVal;
            },
            immediate: true
        },

        config: {
            handler: function (newVal) {
                if (newVal) {
                    this.generatePosterConfig();
                }
            },
            deep: true,
            immediate: true
        }
    }
};
</script>

<style>
.main-poster .poster-share {
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 30rpx 50rpx 10rpx;
}

.main-poster .poster-share .item {
    flex: 1 0 0;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    color: #333;
}

.main-poster .poster-share .item .pic {
    height: 100rpx;
    width: 100rpx;
    background-color: #f2f2f2;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.main-poster .poster-share .item-share {
    margin-top: 15rpx;
}

.main-poster .poster-share .item-share > text {
    margin-top: 15rpx !important;
}

.main-poster .poster-share .item .pic image {
    height: 50rpx;
    width: 50rpx;
}

.main-poster .poster-share .item .pic .friend {
    height: 60rpx;
    width: 60rpx;
}

.main-poster .poster-share .item > text {
    margin-top: 15rpx;
    font-size: 30rpx;
    text-align: center;
}

.main-poster .poster-img {
    display: flex;
    justify-content: center;
    align-items: center;
    padding-top: 0rpx;
    padding-bottom: 0rpx;
    min-height: 600rpx;
    margin-top: 30rpx;
    flex-direction: column;
}

.main-poster .poster-img .save-hint {
    font-size: 30rpx;
    color: #555;
    margin-top: 10rpx;
}

.load.loading::after {
    content: '海报生成中...';
}

.main-poster .poster-img image {
    width: 375rpx;
    border-radius: 15rpx;
}

.main-poster .line {
    width: 100%;
    margin: 30rpx 0 30rpx;
    border-top: 1rpx solid #ddd;
    padding: 30rpx 0 20rpx;
    font-size: 32rpx;
}
</style>
